package com.example.beryl.UtilActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import com.example.beryl.R;
import com.example.beryl.Util.HandlePublic;
import com.example.beryl.Util.NormalProgressDialog;
import com.example.beryl.Util.ReceiveBroadCast;
import com.example.beryl.entity.Action;
import com.example.beryl.entity.UserData.LoginUser;
import com.example.beryl.entity.UserData.Person;
import com.example.beryl.http.Net_userData;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 登录界面
 */
public class MainActivity extends AppCompatActivity {
    private Button btn1;
    private Net_userData dbUtil;
    private static final int account = 1;
    private static final int LU = 2;
    private boolean mReceiverTag = false;//广播注册标志
    HandlePublic handlePublic = new HandlePublic();
    ReceiveBroadCast mBroadcastReceiver = new ReceiveBroadCast();

    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        mReceiverTag = true;
        filter.addAction("com.android.server.scannerservice.broadcast"); //添加过滤条件，接收广播
        registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        SharedPreferences nw_qq = getSharedPreferences("qq_xml",Context.MODE_PRIVATE);
        String role =nw_qq.getString("role","");
        if (role != "")
        {
            final  EditText cNameEditText = findViewById(R.id.username_et);
            cNameEditText.setText(role);//获取用户名
        }
        dbUtil = new Net_userData();
        btn1 = findViewById(R.id.login_bt);
        btn1.setOnClickListener(view -> {
            //hideButton(true);
            //网络行为需要用到线程执行
            checkLoginUser();
        });
        handlePublic.setGetResult((what, t) -> {
            getResult(what,t);
        });
        mBroadcastReceiver.setScanHeadListener(getcode -> {
            if (!NormalProgressDialog.isSuccess)
            {
                return;
            }
            View view = getCurrentFocus();
            handlePublic.getT(view, MainActivity.this);
            //handlePublic.startLoad(this);
            new Thread(() -> getLoginUser(getcode)).start();
        });
        handlePublic.setGetPersonRet(ret -> InsertPeople(ret));
    }


    //获取操作员
    private void getLoginUser(String para)
    {
        List<String> list = new ArrayList<>();
        list = dbUtil.User_CommonMethod(Action.action.GetPerson,para.split("-")[1]);
        handlePublic.setmHandler(LU,list);
    }

    //查询登录用户登录后转向那个页面
    private void checkUser()
    {
        final  EditText cNameEditText = findViewById(R.id.username_et);
        List<String> list = new ArrayList<String>();
        list = dbUtil.User_CommonMethod(Action.action.Login,cNameEditText.getText().toString());
        handlePublic.setmHandler(account,list);
    }

    private void getResult(int what,Object t) throws JSONException {
        String ret = handlePublic.dealDataBase((List)t);
        if (ret.contains("[") || ret.contains("{"))
        {
            switch (what)
            {
                case account:
                    ret = handlePublic.JosnChange(ret);
                    LoginUser loginUser = (LoginUser) handlePublic.getEntity(ret,LoginUser.class);
                    Action.loginUser = loginUser;
                    SharedPreferences.Editor Name_xml = getSharedPreferences("qq_xml",MODE_PRIVATE).edit();
                    Name_xml.putString("role",loginUser.LoginUser);
                    Name_xml.putString("process",loginUser.cProcess);
                    Name_xml.apply();
                    //PhoneDate();
                    //获取返回的页面走向信息
                    // String role = list.get(0).toString();
                    //根据role转到下一个页面
                    //把role传值到下一个页面
                    InsertAccountData(loginUser.LoginUser);

                    unregisterReceiver(mBroadcastReceiver);
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, com.example.beryl.produce.produceIndex.class);
                    intent.putExtra("info1",loginUser.homePage);
                    startActivity(intent);
                    break;
                case LU:
                    selectPM(ret);
                    break;
            }
        }else
        {
            handlePublic.Alert(ret,this);
        }
    }

    //选择操作员
    private void  selectPM(String ret) throws JSONException {
        String rets = "";
        rets = handlePublic.JosnChange(ret);
        JSONArray jsonret = new JSONArray(rets);
        //如果返回数据大于1
        if (jsonret.length() > 1)
        {
            handlePublic.AlterDialog(MainActivity.this,jsonret);
        }
        else
        {
            //返回一条数据时
            InsertPeople(ret);
        }
    }

    private void InsertPeople(String para)
    {
        Gson gson = new Gson();
        Person EM = gson.fromJson(para, Person.class);
        Action.person = EM;
        EditText editText2 = findViewById(R.id.password_et);
        editText2.setText(EM.cPsn_Name);
    }

    private void checkLoginUser() {
        final  EditText cNameEditText = findViewById(R.id.password_et);
        if (!cNameEditText.getText().toString().equals(""))
        {
            //handlePublic.startLoad(this);
            new Thread(() -> checkUser()).start();
        }
        else
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("提示");
            builder.setMessage("员工码没扫描，是否继续？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //handlePublic.startLoad(MainActivity.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            checkUser();
                        }
                    }).start();
                }
            });
            builder.setNegativeButton("否",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
        }
    }

    private void PhoneDate()
    {
        HandlePublic handlePublic = new HandlePublic();
        HashMap<String,String> hashMap = new HashMap<>();
        if (Action.MAC != "" && Action.loginUser != null)
        {
            hashMap.put("账号",Action.loginUser.LoginUser);
            hashMap.put("MAC",Action.MAC);
            Action.PhoneMessage = handlePublic.MakeJson(hashMap);
        }
    }

    @Override
    public void onBackPressed() {
        if (mReceiverTag) {
            unregisterReceiver(mBroadcastReceiver);
            finish();
        }
    }

    private void InsertAccountData(String account)
    {
        String mac = handlePublic.get();
        try {
            String tex = HandlePublic.readLogFile(Action.LoginJson,Action.LoginJson);
            if (tex == "")
            {
                HandlePublic.inseryt(account+"," + mac,Action.LoginJson,Action.LoginJson);
            }else
            {
                String acc = tex.split(",")[0];
                if (acc != account)
                {
                    HandlePublic.inseryt(account+"," + mac,Action.LoginJson,Action.LoginJson);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}